package com.testJob.config;

import com.testJob.job.IndexJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.Task;

import java.lang.reflect.Method;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @Author：Administrator
 * @Date：2022/8/22/0022 21:31
 * @Versiion：1.0
 */
@Configuration
@Slf4j
public class ScheduleThreadPoolConfig implements SchedulingConfigurer {
    /**
     * Callback allowing a {@link TaskScheduler
     * TaskScheduler} and specific {@link Task Task}
     * instances to be registered against the given the {@link ScheduledTaskRegistrar}.
     *
     * @param taskRegistrar the registrar to be configured.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        Method[] methods = IndexJob.class.getMethods();
        int defaultPoolSize = 10;
        int corePoolSize = 0;
        if(null != methods && methods.length > 0){
            for (Method method : methods) {
                Scheduled annotation = method.getAnnotation(Scheduled.class);
                if (null != annotation) {
                    corePoolSize += 1;
                }
            }
        }
        log.info("线程池容量:{}",corePoolSize);
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(corePoolSize>defaultPoolSize?defaultPoolSize:corePoolSize);
        taskRegistrar.setScheduler(scheduledThreadPoolExecutor);
    }
}
